package com.example.lib.widget

import android.content.Context
import android.os.Handler
import android.os.Looper
import android.util.AttributeSet
import android.widget.ProgressBar
import androidx.core.view.isVisible
import com.example.lib.extend.gone
import com.example.lib.extend.visi

class CountDownProgress @JvmOverloads constructor(context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0) : ProgressBar(context, attrs, defStyleAttr) {
    private var time: Long = 0
    private var flag = false//false为减 true为加
    private var onOver: () -> Unit = {}
    private val mHandler = Handler(Looper.myLooper()!!)

    private val countDownRunnable = Runnable {
        countDown()
    }

    private fun countDown() {
            if (flag) time += 500
            else time -= 500
            if (time <= 0) {
                onOver.invoke()
            } else {
                mHandler.postDelayed(countDownRunnable, 500)
            }
    }

    /**
     * 设置开始时间
     * 单位：秒
     */
    fun setTime(t: Long) {
        cancel()
        if (flag.not()) {
            if (t < 0) {
                gone()
                onOver.invoke()
                return
            } else visi()
        }
        this.time = t
        mHandler.post(countDownRunnable)
    }

    fun setOnOverListener(onOver: () -> Unit) {
        this.onOver = onOver
    }

    fun cancel() {
        mHandler.removeCallbacksAndMessages(null)
        time = 0
    }

    fun destroy() {
        mHandler.removeCallbacksAndMessages(null)
    }
}